package com.pzhu.file.utils;


import com.pzhu.acargid.until.Result;
import org.slf4j.Logger;
import org.springframework.util.StreamUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;


public class FileUtil {

    private static final String MAIN_DIRECTORY_NAME = "file";


    public static String getSavePath(Integer userid, String type) {
        String userDir = System.getenv("FILE_FOLDER");
        if (userDir == null) {
            userDir = System.getProperty("user.dir");
        }
        if (userDir.endsWith("bin")) {
            userDir = userDir.substring(0, userDir.length() - 4);
        } else {
            String separator = File.separator;
            if (userDir.endsWith(MAIN_DIRECTORY_NAME)) {
                userDir = userDir + separator + userid + separator + type + separator;
            } else {
                userDir = userDir + separator + MAIN_DIRECTORY_NAME + separator + userid + separator + type + separator;
            }
        }
        //user.dir/userid/type/
        return userDir;
    }

    public static Result saveFile(String savePath, MultipartFile multipartFile, Logger logger) {
        File outFile = new File(savePath);
        if (!outFile.exists() && !outFile.mkdirs()) {
            logger.error("创建文件夹【{}】失败，请检查目录权限！", savePath);
        }
        String filename = multipartFile.getOriginalFilename();
        logger.info("上传文件：{}{}", savePath, filename);
        try (InputStream in = multipartFile.getInputStream(); OutputStream out = Files.newOutputStream(Paths.get(savePath + File.separator + filename))) {
            StreamUtils.copy(in, out);
            return Result.success(null);
        } catch (IOException e) {
            logger.error("文件上传失败", e);
            return Result.failure(null);
        }
    }

    public static void makeDir(String savePath, Logger logger) {
        File outFile = new File(savePath);
        if (!outFile.exists() && !outFile.mkdirs()) {
            logger.error("创建文件夹【{}】失败，请检查目录权限！", savePath);
        }
        logger.info("上传文件：{}", savePath);
    }
}
